package com.wowangz.cms.systemmanage.country.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.city.pojo.City;
import com.wowangz.cms.systemmanage.country.pojo.Country;
import com.wowangz.cms.systemmanage.country.service.CountryService;

@Scope("prototype")
@Controller
public class CountryController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(CountryController.class);
	
	/**
	 * 点击菜单"国家信息管理"显示“国家信息管理”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/country/queryCountryList.web")
	public String queryProvinceList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/country/countryList";
	}
	
	/**
	 * 打开“国家信息管理”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/country/queryCountryListInfoDataGrid.json")
	public void queryCityListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, false);
			long resultCount = countryService.findResultCount(map);
			List<City> resultList = countryService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("countrycode", DataTypeConstant.STRING);
			dataStyle.addDepict("countryname", DataTypeConstant.STRING);
			dataStyle.addDepict("countrydesc", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转国家信息添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/country/toAddCountry.web")
	public String toAddCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/country/countryAdd";
	}
	
	/**
	 * 新增国家信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/country/addCountry.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		Country country = null;
		try {
			country = (Country) ServletUtils.getParametersToBaseEntity(request, Country.class);
			country.setInputtime(new Date());
			country.setInputuserid(userContext.getLoginUser().getId());
			country.setModifytime(new Date());
			country.setModifyuserid(userContext.getLoginUser().getId());
			country.setStatusid(SysConstant.RecordStatus.VALID);
			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, true);
			
			countryService.add(country);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/country/countryAdd";
	}
	
	@RequestMapping(value = "/systemmanage/country/validattionCountry.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Country country = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			country = (Country) ServletUtils.getParametersToBaseEntity(request, Country.class);
			
			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != country.getId()){
				map.put("id", country.getId());
			}
			map.put("countrycode", country.getCountrycode());
			if(!countryService.validationCity(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.country.check.countrycode"));
			}
			map.remove("countrycode");
			map.put("countryname", country.getCountryname());
			if(!countryService.validationCity(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.country.check.countryname"));
			}
			map.remove("countryname");
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改国家信息页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/country/toUpdateCountry")
	public String toUpdateCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String countryId = getRequest().getParameter("id");
			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, false);
			Country country = countryService.findCountryById(countryId);
			
			model.addAttribute("country", country);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/country/countryUpdate";
	}
	
	/**
	 * 修改国家信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/country/updateCountry.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateCountry(HttpServletRequest request, HttpServletResponse response, Model model) {
		Country country = null;
		try {
			country = (Country) ServletUtils.getParametersToBaseEntity(request, Country.class);
			country.setModifytime(new Date());
			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, true);
			countryService.update(country);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/systemmanage/country/countryUpdate";
	}
	
	/**
	 * 删除国家信息
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/country/deleteCountry.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long countryId = Long.valueOf(getRequest().getParameter("id"));
			Country country = new Country();
			country.setId(countryId);
			country.setStatusid(SysConstant.RecordStatus.INVALID);
			CountryService countryService = (CountryService) IssTransactionContainer.getInstance(CountryService.class, false);
			countryService.update(country);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}
}
